package com.guoyh.bilui.bottombar

import android.content.Context
import android.widget.LinearLayout
import com.airbnb.lottie.LottieAnimationView
import android.widget.TextView
import kotlin.jvm.JvmOverloads
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import com.guoyh.bilui.R
import com.guoyh.bilui.utils.UIUtils
import android.widget.FrameLayout
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import com.guoyh.baseutils.mylog.Loger
import android.widget.ImageView
import com.guoyh.baseutils.ext.sp2px
import com.guoyh.baseutils.utils.animRubberband
import java.util.*

/**
 * @author ChayChan
 * @description: 底部tab条目
 * @date 2017/6/23  9:14
 */
class BottomBarItem : LinearLayout {
    private var normalIcon //普通状态图标的资源id
            : Drawable? = null
    private var selectedIcon //选中状态图标的资源id
            : Drawable? = null
    private var selectedIconColor //选中状态图标的 颜色
            : Int? = null
    private var normalIconColor //选中状态图标的 颜色
            : Int? = null
    private var title //文本
            : String? = null
    private var titleTextBold = false //文字加粗
    private var titleTextSize = 12 //文字大小 默认为12sp
    private var titleNormalColor //描述文本的默认显示颜色
            = 0
    private var titleSelectedColor //述文本的默认选中显示颜色
            = 0
    private var marginTop = 0 //文字和图标的距离,默认0dp
    private var openTouchBg = false // 是否开启触摸背景，默认关闭
    private var touchDrawable //触摸时的背景
            : Drawable? = null
    private var iconWidth //图标的宽度
            = 0
    private var iconHeight //图标的高度
            = 0
    private var itemPadding //BottomBarItem的padding
            = 0
    private var unreadTextSize = 10 //未读数默认字体大小10sp
    var unreadNumThreshold = 99 //未读数阈值
    private var unreadTextColor //未读数字体颜色
            = 0
    private var unreadTextBg //未读数字体背景
            : Drawable? = null
    private var msgTextSize = 6 //消息默认字体大小6sp
    private var msgTextColor //消息文字颜色
            = 0
    private var msgTextBg //消息文字背景
            : Drawable? = null
    private var notifyPointBg //小红点背景
            : Drawable? = null
    private var lottieJson //lottie文件名
            : String? = null
    private var useLottie = false

    lateinit var imageView: ImageView
    lateinit var mLottieView: LottieAnimationView
    lateinit  var textView: TextView


    private var mTvUnread: TextView? = null
    private var mTvNotify: TextView? = null
    private var mTvMsg: TextView? = null


    constructor(context: Context?) : super(context) {}

    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.BottomBarItem)
        initAttrs(ta) //初始化属性
        ta.recycle()
        checkValues() //检查值是否合法
        init() //初始化相关操作
    }

    private fun initAttrs(ta: TypedArray) {
        normalIcon = ta.getDrawable(R.styleable.BottomBarItem_iconNormal)
        selectedIcon = ta.getDrawable(R.styleable.BottomBarItem_iconSelected)
        title = ta.getString(R.styleable.BottomBarItem_itemText)
        titleTextBold = ta.getBoolean(R.styleable.BottomBarItem_itemTextBold, titleTextBold)
        titleTextSize = ta.getDimensionPixelSize(
            R.styleable.BottomBarItem_itemTextSize,
            UIUtils.sp2px(context, titleTextSize.toFloat())
        )
        titleNormalColor =
            ta.getColor(R.styleable.BottomBarItem_textColorNormal, UIUtils.getColorm("#999999"))
        titleSelectedColor =
            ta.getColor(R.styleable.BottomBarItem_textColorSelected, UIUtils.getColorm("#333333"))
        marginTop = ta.getDimensionPixelSize(
            R.styleable.BottomBarItem_itemMarginTop,
            UIUtils.dip2Px(context, marginTop)
        )
        openTouchBg = ta.getBoolean(R.styleable.BottomBarItem_openTouchBg, openTouchBg)
        touchDrawable = ta.getDrawable(R.styleable.BottomBarItem_touchDrawable)
        iconWidth = ta.getDimensionPixelSize(R.styleable.BottomBarItem_iconWidth, 0)
        iconHeight = ta.getDimensionPixelSize(R.styleable.BottomBarItem_iconHeight, 0)
        itemPadding = ta.getDimensionPixelSize(R.styleable.BottomBarItem_itemPadding, 0)
        unreadTextSize = ta.getDimensionPixelSize(
            R.styleable.BottomBarItem_unreadTextSize,
            UIUtils.sp2px(context, unreadTextSize.toFloat())
        )
        unreadTextColor =
            ta.getColor(R.styleable.BottomBarItem_unreadTextColor, UIUtils.getColorm("#ffffff"))
        unreadTextBg = ta.getDrawable(R.styleable.BottomBarItem_unreadTextBg)
        msgTextSize = ta.getDimensionPixelSize(
            R.styleable.BottomBarItem_msgTextSize,
            UIUtils.sp2px(context, msgTextSize.toFloat())
        )
        msgTextColor =
            ta.getColor(R.styleable.BottomBarItem_msgTextColor, UIUtils.getColorm("#ffffff"))
        msgTextBg = ta.getDrawable(R.styleable.BottomBarItem_msgTextBg)
        notifyPointBg = ta.getDrawable(R.styleable.BottomBarItem_notifyPointBg)
        unreadNumThreshold =
            ta.getInteger(R.styleable.BottomBarItem_unreadThreshold, unreadNumThreshold)
        lottieJson = ta.getString(R.styleable.BottomBarItem_lottieJson)
        useLottie = !TextUtils.isEmpty(lottieJson)
    }

    /**
     * 检查传入的值是否完善
     */
    private fun checkValues() {
        check(!(!useLottie && normalIcon == null)) { "You have not set the normal icon" }
        check(!(!useLottie && selectedIcon == null)) { "You have not set the selected icon" }
        check(!(openTouchBg && touchDrawable == null)) {
            //如果有开启触摸背景效果但是没有传对应的drawable
            "Touch effect is turned on, but touchDrawable is not specified"
        }
        if (unreadTextBg == null) {
            unreadTextBg = resources.getDrawable(R.drawable.shape_unread)
        }
        if (msgTextBg == null) {
            msgTextBg = resources.getDrawable(R.drawable.shape_msg)
        }
        if (notifyPointBg == null) {
            notifyPointBg = resources.getDrawable(R.drawable.shape_notify_point)
        }
    }

    private fun init() {
        orientation = VERTICAL
        gravity = Gravity.CENTER
        val view = initView()
        val layoutParams = imageView!!.layoutParams as FrameLayout.LayoutParams
        if (iconWidth != 0 && iconHeight != 0) {
            //如果有设置图标的宽度和高度，则设置ImageView的宽高
            layoutParams.width = iconWidth
            layoutParams.height = iconHeight
        }
        if (useLottie) {
            mLottieView!!.layoutParams = layoutParams
            mLottieView!!.setAnimation(lottieJson)
            mLottieView!!.repeatCount = 0
        } else {
            imageView!!.setImageDrawable(normalIcon)
            imageView!!.layoutParams = layoutParams
        }
        if (normalIconColor != -1) {
            UIUtils.setImageViewColor(imageView, normalIconColor!!)
        }
        textView!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleTextSize.toFloat()) //设置底部文字字体大小
        textView!!.paint.isFakeBoldText = titleTextBold
        mTvUnread!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, unreadTextSize.toFloat()) //设置未读数的字体大小
        mTvUnread!!.setTextColor(unreadTextColor) //设置未读数字体颜色
        mTvUnread!!.background = unreadTextBg //设置未读数背景
        mTvMsg!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, msgTextSize.toFloat()) //设置提示文字的字体大小
        mTvMsg!!.setTextColor(msgTextColor) //设置提示文字的字体颜色
        mTvMsg!!.background = msgTextBg //设置提示文字的背景颜色
        mTvNotify!!.background = notifyPointBg //设置提示点的背景颜色
        textView!!.setTextColor(titleNormalColor) //设置底部文字字体颜色
        textView!!.text = title //设置标签文字
        val textLayoutParams = textView!!.layoutParams as LayoutParams
        //        textLayoutParams.topMargin = marginTop;
//        textLayoutParams.bottomMargin = marginTop;
        textView!!.layoutParams = textLayoutParams
        if (openTouchBg) {
            //如果有开启触摸背景
            background = touchDrawable
        }
        addView(view)
    }

    private fun initView(): View {
        val view = inflate(context, R.layout.libui_item_bottom_bar, null)
        if (itemPadding != 0) {
            //如果有设置item的padding
            view.setPadding(itemPadding, itemPadding, itemPadding, itemPadding)
        }
        imageView = view.findViewById(R.id.iv_icon)
        mLottieView = view.findViewById(R.id.lottieView)
        mTvUnread = view.findViewById(R.id.tv_unred_num)
        mTvMsg = view.findViewById(R.id.tv_msg)
        mTvNotify = view.findViewById(R.id.tv_point)
        textView = view.findViewById(R.id.tv_text)
        imageView.setVisibility(if (useLottie) GONE else VISIBLE)
        mLottieView.setVisibility(if (useLottie) VISIBLE else GONE)
        return view
    }

    fun setNormalIcon(normalIcon: Drawable?) {
        this.normalIcon = normalIcon
        Loger.dd("============")
        refreshTab()
    }

    fun setNormalIcon(resId: Int) {
        setNormalIcon(UIUtils.getDrawable(context, resId))
    }

    fun setSelectedIcon(selectedIcon: Drawable?) {
        this.selectedIcon = selectedIcon
        Loger.dd("============")
        refreshTab()
    }

    fun setSelectedIcon(resId: Int) {
        setSelectedIcon(UIUtils.getDrawable(context, resId))
    }

    fun refreshTab(isSelected: Boolean) {
        setSelected(isSelected)
        refreshTab()
    }

    fun refreshTab() {
        if (useLottie) {
            if (isSelected) {
                mLottieView!!.playAnimation()
            } else {
                //取消动画 进度设置为0
                mLottieView!!.cancelAnimation()
                mLottieView!!.progress = 0f
            }
        } else {
            if (isSelected) {
                imageView.animRubberband()
            } else {
                clearAnimation()
            }
            imageView!!.setImageDrawable(if (isSelected) selectedIcon else normalIcon)
            if (selectedIconColor != -1 && normalIconColor != -1) {
                UIUtils.setImageViewColor(
                    imageView,
                    (if (isSelected) selectedIconColor else normalIconColor)!!
                )
            }
        }
        Loger.dd("=====-=-=-=-=-=-=" + isSelected)
        textView!!.setTextColor(if (isSelected) titleSelectedColor else titleNormalColor)
    }

    fun setColor(
        titleSelectedColor: Int,
        titleNormalColor: Int,
        selectedIconColor: Int,
        normalIconColor: Int
    ) {
        this.normalIconColor = normalIconColor
        this.selectedIconColor = selectedIconColor
        this.titleNormalColor = titleNormalColor
        this.titleSelectedColor = titleSelectedColor
        refreshTab()
    }

    private fun setTvVisible(tv: TextView?) {
        //都设置为不可见
        mTvUnread!!.visibility = GONE
        mTvMsg!!.visibility = GONE
        mTvNotify!!.visibility = GONE
        tv!!.visibility = VISIBLE //设置为可见
    }

    fun setUnreadNum(unreadNum: Int) {
        setTvVisible(mTvUnread)
        if (unreadNum <= 0) {
            mTvUnread!!.visibility = GONE
        } else if (unreadNum <= unreadNumThreshold) {
            mTvUnread!!.text = unreadNum.toString()
        } else {
            mTvUnread!!.text = String.format(Locale.CHINA, "%d+", unreadNumThreshold)
        }
    }

    fun setMsg(msg: String?) {
        setTvVisible(mTvMsg)
        mTvMsg!!.text = msg
    }

    fun hideMsg() {
        mTvMsg!!.visibility = GONE
    }

    fun showNotify() {
        setTvVisible(mTvNotify)
    }

    fun hideNotify() {
        mTvNotify!!.visibility = GONE
    }

    fun create(builder: Builder): BottomBarItem {
        normalIcon = builder.normalIcon
        selectedIcon = builder.selectedIcon
        selectedIconColor = builder.selectedIconColor
        normalIconColor = builder.normalIconColor
        title = builder.title
        titleTextBold = builder.titleTextBold
        titleTextSize = builder.titleTextSize
        titleNormalColor = builder.titleNormalColor
        titleSelectedColor = builder.titleSelectedColor
        marginTop = builder.marginTop
        openTouchBg = builder.openTouchBg
        touchDrawable = builder.touchDrawable
        iconWidth = builder.iconWidth
        iconHeight = builder.iconHeight
        itemPadding = builder.itemPadding
        unreadTextSize = builder.unreadTextSize
        unreadTextColor = builder.unreadTextColor
        unreadTextBg = builder.unreadTextBg
        unreadNumThreshold = builder.unreadNumThreshold
        msgTextSize = builder.msgTextSize
        msgTextColor = builder.msgTextColor
        msgTextBg = builder.msgTextBg
        notifyPointBg = builder.notifyPointBg
        lottieJson = builder.lottieJson
        checkValues()
        init()
        return this
    }

    class Builder(val context: Context) {
        var normalIcon //普通状态图标的资源id
                : Drawable? = null
        var selectedIcon //选中状态图标的资源id
                : Drawable? = null
        var selectedIconColor //选中状态图标的颜色
                : Int? = null
        var normalIconColor //选中状态图标的颜色
                : Int? = null
        var title //标题
                : String? = null
        var titleTextBold //文字加粗
                = false
        var titleTextSize //字体大小
                : Int
        var titleNormalColor //描述文本的默认显示颜色
                : Int
        var titleSelectedColor //述文本的默认选中显示颜色
                : Int
        var marginTop //文字和图标的距离
                = 0
        var openTouchBg // 是否开启触摸背景，默认关闭
                = false
        var touchDrawable //触摸时的背景
                : Drawable? = null
        var iconWidth //图标的宽度
                = 0
        var iconHeight //图标的高度
                = 0
        var itemPadding //BottomBarItem的padding
                = 0
        var unreadTextSize //未读数字体大小
                : Int
        var unreadNumThreshold //未读数阈值
                : Int
        var unreadTextColor //未读数字体颜色
                : Int
        var unreadTextBg //未读数文字背景
                : Drawable? = null
        var msgTextSize //消息字体大小
                : Int
        var msgTextColor //消息文字颜色
                : Int
        var msgTextBg //消息提醒背景颜色
                : Drawable? = null
        var notifyPointBg //小红点背景颜色
                : Drawable? = null
        var lottieJson //lottie文件名
                : String? = null

        /**
         * Sets the default icon's resourceId
         */
        fun normalIcon(normalIcon: Drawable?): Builder {
            this.normalIcon = normalIcon
            return this
        }

        /**
         * Sets the selected icon's resourceId
         */
        fun selectedIcon(selectedIcon: Drawable?): Builder {
            this.selectedIcon = selectedIcon
            return this
        }

        fun selectedIconColor(selectedIconColor: Int): Builder {
            this.selectedIconColor = selectedIconColor
            return this
        }

        fun normalIconColor(normalIconColor: Int): Builder {
            this.normalIconColor = normalIconColor
            return this
        }

        /**
         * Sets the title's resourceId
         */
        fun title(titleId: Int): Builder {
            title = context.getString(titleId)
            return this
        }

        /**
         * Sets the title string
         */
        fun title(title: String?): Builder {
            this.title = title
            return this
        }

        /**
         * Sets the title's text bold
         */
        fun titleTextBold(titleTextBold: Boolean): Builder {
            this.titleTextBold = titleTextBold
            return this
        }

        /**
         * Sets the title's text size
         */
        fun titleTextSize(titleTextSize: Int): Builder {
            this.titleTextSize = sp2px(titleTextSize.toFloat())
            return this
        }

        /**
         * Sets the title's normal color resourceId
         */
        fun titleNormalColor(titleNormalColor: Int): Builder {
            this.titleNormalColor = titleNormalColor
            return this
        }

        /**
         * Sets the title's selected color resourceId
         */
        fun titleSelectedColor(titleSelectedColor: Int): Builder {
            this.titleSelectedColor = titleSelectedColor
            return this
        }

        /**
         * Sets the item's margin top
         */
        fun marginTop(marginTop: Int): Builder {
            this.marginTop = marginTop
            return this
        }

        /**
         * Sets whether to open the touch background effect
         */
        fun openTouchBg(openTouchBg: Boolean): Builder {
            this.openTouchBg = openTouchBg
            return this
        }

        /**
         * Sets touch background
         */
        fun touchDrawable(touchDrawable: Drawable?): Builder {
            this.touchDrawable = touchDrawable
            return this
        }

        /**
         * Sets icon's width
         */
        fun iconWidth(iconWidth: Int): Builder {
            this.iconWidth = UIUtils.dip2Px(context, iconWidth)
            return this
        }

        /**
         * Sets icon's height
         */
        fun iconHeight(iconHeight: Int): Builder {
            this.iconHeight = UIUtils.dip2Px(context, iconHeight)
            return this
        }

        /**
         * Sets padding for item
         */
        fun itemPadding(itemPadding: Int): Builder {
            this.itemPadding = UIUtils.dip2Px(context, itemPadding)
            return this
        }

        /**
         * Sets unread font size
         */
        fun unreadTextSize(unreadTextSize: Int): Builder {
            this.unreadTextSize = UIUtils.sp2px(context, unreadTextSize.toFloat())
            return this
        }

        /**
         * Sets the number of unread array thresholds greater than the threshold to be displayed as n + n as the set threshold
         */
        fun unreadNumThreshold(unreadNumThreshold: Int): Builder {
            this.unreadNumThreshold = unreadNumThreshold
            return this
        }

        /**
         * Sets the message font size
         */
        fun msgTextSize(msgTextSize: Int): Builder {
            this.msgTextSize = UIUtils.sp2px(context, msgTextSize.toFloat())
            return this
        }

        /**
         * Sets the message font background
         */
        fun unreadTextBg(unreadTextBg: Drawable?): Builder {
            this.unreadTextBg = unreadTextBg
            return this
        }

        /**
         * Sets unread font color
         */
        fun unreadTextColor(unreadTextColor: Int): Builder {
            this.unreadTextColor = unreadTextColor
            return this
        }

        /**
         * Sets the message font color
         */
        fun msgTextColor(msgTextColor: Int): Builder {
            this.msgTextColor = msgTextColor
            return this
        }

        /**
         * Sets the message font background
         */
        fun msgTextBg(msgTextBg: Drawable?): Builder {
            this.msgTextBg = msgTextBg
            return this
        }

        /**
         * Set the message prompt point background
         */
        fun notifyPointBg(notifyPointBg: Drawable?): Builder {
            this.notifyPointBg = notifyPointBg
            return this
        }

        /**
         * Set the name of lottie json file
         */
        fun lottieJson(lottieJson: String?): Builder {
            this.lottieJson = lottieJson
            return this
        }
        /**
         * Create a BottomBarItem object
         */
        fun create(normalIcon: Drawable?, selectedIcon: Drawable?, text: String?): BottomBarItem {
            this.normalIcon = normalIcon
            this.selectedIcon = selectedIcon
            title = text
            val bottomBarItem = BottomBarItem(context)
            return bottomBarItem.create(this)
        }

        fun create(normalIconId: Int, selectedIconId: Int, text: String?): BottomBarItem {
            return create(
                UIUtils.getDrawable(context, normalIconId),
                UIUtils.getDrawable(context, selectedIconId),
                text
            )
        }

        init {
            titleTextSize = UIUtils.sp2px(context, 12f)
            titleNormalColor = UIUtils.getColorm("#999999")
            titleSelectedColor = UIUtils.getColorm("#333333")
            unreadTextSize = UIUtils.sp2px(context, 10f)
            msgTextSize = UIUtils.sp2px(context, 6f)
            unreadTextColor = UIUtils.getColorm("#ffffff")
            unreadNumThreshold = 99
            msgTextColor = UIUtils.getColorm("#ffffff")
        }
    }
}